<?php
/**
 * ViewRenderer.php
 *
 * @category    Madoqua
 * @package     Controller
 * @subpackage  Helper
 */

/** base class */
require_once 'Zend/Controller/Action/Helper/ViewRenderer.php';

/**
 * Madoqua_Controller_Action_Helper_ViewRenderer
 *
 * @category    Madoqua
 * @package     Controller
 * @subpackage  Helper
 */
class Madoqua_Controller_Action_Helper_ViewRenderer extends Zend_Controller_Action_Helper_ViewRenderer
{
    /**
     * overloaded renderscript, checks whether a themed version exists then uses that over the default
     *
     * @param string $script
     * @param string $name
     */
    public function renderScript($script, $name = null)
    {
        $request = $this->getRequest();
        //ha! damn request. You thought you could get away by being cloned...
        //but I found you!
        
        if (in_array($request->getModuleName(), array('front', 'blog'))) {
            //only allow themening for front and blog modules        
            
            $config = Madoqua_Application::getConfiguration();
            //application config
    
            $themePath = Madoqua_Application::getDataDirectory() . DIRECTORY_SEPARATOR  . 'themes/' . $config->theme->active .  '/views/';
            //path to the theme directory for view scripts
            
            $newScript = str_replace('/', '-', $script);
            //don't use subdirs
    
            $themeScript = $themePath . $newScript;
            //the themed view script, should it exist
            
            if (Zend_Loader::isReadable($themeScript)) {
                //woo, it exists! \ó/
                $paths = $this->view->getScriptPaths();
                //old script paths
                $this->view->setScriptPath($themePath);
                //set single new script path
                
                if (null === $name) {
                    $name = $this->getResponseSegment();
                }
        
                $this->getResponse()->appendBody(
                    $this->view->render($newScript),
                    $name
                );
                $this->setNoRender();                
                //render the view script
                $this->view->setScriptPath($paths);
                //reset the script paths
                return;
            }
            //ahw... it doesn't exist :(
        }
        parent::renderScript($script, $name);
        //let the normal view renderer do it's job then :x        
    }
}
